﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Presentation.PropertyEditing;
using System.Activities.Statements;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Windows.Markup;

namespace Vision.Core.ActivityComponents.Xml
{
    /// <summary>
    /// 
    /// </summary>
    [ContentProperty("Body")]
    [System.ComponentModel.Designer(typeof(XmlOpenDesigner))]
    public class XmlOpen : NativeActivity
    {
        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        public InArgument<byte[]> FileData { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Output")]
        public OutArgument<XmlDocument> XmlDocument { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Browsable(false)]
        [DefaultValue(null)]
        public ActivityAction<XmlDocument> Body { get; set; }

        public XmlOpen()
        {
            this.Body = new ActivityAction<XmlDocument>()
            {
                Argument = new DelegateInArgument<XmlDocument>()
                {
                    Name = "xmlDocument"
                }
            };
        }

        protected override void CacheMetadata(NativeActivityMetadata metadata)
        {
            RuntimeArgument fileDataArgument = new RuntimeArgument("FileData", typeof(byte[]), ArgumentDirection.In, true);
            metadata.Bind(this.FileData, fileDataArgument);
            metadata.AddArgument(fileDataArgument);

            RuntimeArgument xmlDocumentArgument = new RuntimeArgument("XmlDocument", typeof(XmlDocument), ArgumentDirection.Out, false);
            metadata.Bind(this.XmlDocument, xmlDocumentArgument);
            metadata.AddArgument(xmlDocumentArgument);

            metadata.AddDelegate(this.Body);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            XmlDocument xmlDocument = new XmlDocument();
            using (MemoryStream mStream = new MemoryStream(this.FileData.Get(context))){
                xmlDocument.Load(mStream);
            }
            this.XmlDocument.Set(context, xmlDocument);

            // schedule the next action
            if (this.Body != null && this.Body.Handler != null)
            {
                context.ScheduleAction(this.Body, xmlDocument);
            }  
        }
    }
}
